package io.wongxd.demo

import android.app.Application
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ProcessLifecycleOwner
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import coil.ImageLoader
import coil.ImageLoaderFactory
import com.tencent.mmkv.MMKV
import io.modifier.basic.emo.core.EmoLog
import io.modifier.basic.emo.core.EmoLogDelegate
import io.modifier.basic.emo.network.NetworkBandwidthSampler
import io.modifier.basic.emo.scheme.SchemeClient
import io.modifier.basic.emo.scheme.SchemeHandler
import io.modifier.basic.emo.scheme.SchemeInterceptor
import io.modifier.basic.emo.scheme.SchemeParts
import io.modifier.basic.emo.scheme.SchemeTransaction
import io.modifier.basic.emo.scheme.impl.schemeClient
import io.wongxd.solution.WSolution
import io.wongxd.solution.camerax.Camera2ConfigProvider
import io.wongxd.solution.log.xlog.FLog
import io.wongxd.solution.log.xlog.FLogLevel
import io.wongxd.solution.log.xlog.FLogger
import kotlinx.coroutines.launch

lateinit var EmoScheme: SchemeClient
    private set

class App : Application(), Camera2ConfigProvider, ImageLoaderFactory {

    override fun onCreate() {
        super.onCreate()
        WSolution.init(this)

        initXlog()

        initEmo()
    }

    private fun initXlog() {
        // 初始化
        FLog.init(
            //（必传参数）日志文件目录
            directory = filesDir.resolve("app_log"),

            // 单元测试使用的调度器
//            dispatcher = TestLogDispatcher(),
        )

        // 设置日志等级 All, Verbose, Debug, Info, Warning, Error, Off  默认日志等级：All
        FLog.setLevel(FLogLevel.All)

        // 限制每天日志文件大小(单位MB)，小于等于0表示不限制，默认不限制
        FLog.setLimitMBPerDay(100)

        // 设置是否打打印控制台日志，默认打开
        FLog.setConsoleLogEnabled(true)

        // 修改某个日志标识的配置信息
        FLog.config<AppLogger> {
            this.level = FLogLevel.All
            this.tag = "AppLoggerAppLogger"
        }

        /**
         * 删除日志，参数saveDays表示要保留的日志天数，小于等于0表示删除全部日志，
         * 此处saveDays=1表示保留1天的日志，即保留当天的日志
         */
        FLog.deleteLog(1)
    }


    private fun initEmo() {
        EmoScheme = schemeClient(this) {
            addInterceptor(object : SchemeInterceptor {
                override suspend fun intercept(env: SchemeTransaction, schemeParts: SchemeParts, next: SchemeHandler): Boolean {
                    Log.i("EmoDemo", "begin handle scheme: ${schemeParts.origin}")
                    val ret = next.run(env, schemeParts)
                    Log.i("EmoDemo", "after handle scheme: ${schemeParts.origin}, ret = $ret")
                    return ret
                }
            })
        }

        EmoLog.delegate = object : EmoLogDelegate {
            override fun e(tag: String, msg: String, throwable: Throwable?) {
                Log.e(tag, msg, throwable)
            }

            override fun w(tag: String, msg: String, throwable: Throwable?) {
                Log.w(tag, msg, throwable)
            }

            override fun i(tag: String, msg: String, throwable: Throwable?) {
                Log.i(tag, msg, throwable)
            }

            override fun d(tag: String, msg: String, throwable: Throwable?) {
                Log.d(tag, msg, throwable)
            }
        }
        MMKV.initialize(this)
        NetworkBandwidthSampler.of(this).startSampling()
        ProcessLifecycleOwner.get().lifecycleScope.launch {
            ProcessLifecycleOwner.get().repeatOnLifecycle(Lifecycle.State.STARTED) {
//                reportWake("EMO")
            }
        }
    }

    override fun newImageLoader(): ImageLoader {
        return ImageLoader.Builder(applicationContext)
            .crossfade(true)
            .build()
    }

}

/**
 * 定义一个日志标识，默认tag为短类名：AppLogger
 */
interface AppLogger : FLogger